package com.healthcarex.hip.saas.web.rest;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.healthcarex.hip.saas.common.util.BeanUtils;
import com.healthcarex.hip.saas.web.annotation.WebLog;
import com.healthcarex.hip.saas.security.config.SecurityProperties;
import com.healthcarex.hip.saas.security.util.SecurityUtils;
import com.healthcarex.hip.saas.common.model.BaseModel;
import com.healthcarex.hip.saas.mybatis.service.IBaseService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.Authorization;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * @author chenpan
 * @ClassName: BaseCRUDRestController
 * description: 基础CRUD 控制器
 * @date 2018-04-03 17:30
 */

public abstract class BaseCRUDRestController<T extends BaseModel> {

    @Autowired
    protected SecurityProperties securityProperties;

    public String resourceIdentity;

    public void setResourceIdentity(String resourceIdentity) {
        if (StringUtils.isNotBlank(resourceIdentity)) {
            this.resourceIdentity = resourceIdentity;
        }
    }

    @Autowired
    protected IBaseService<T> baseService;

    @GetMapping()
    @ApiOperation(value = "分页查询", authorizations = {@Authorization(value = "apiKey")})
    @WebLog(value = "分页查询")
    public ResponseEntity<PageInfo<List<T>>> pageList(@ApiParam("查询条件实体") T m,
                                   @ApiParam("页码") @RequestParam(name = "pageNo", required = false, defaultValue = "1")
                                           Integer pageNo,
                                   @ApiParam("每页数量") @RequestParam(name = "pageSize", required = false, defaultValue = "10")
                                           Integer pageSize) throws IllegalAccessException {

        pageNo = pageNo == null ? 1 : pageNo;
        pageSize = pageSize == null ? 10 : pageSize;

        PageHelper.startPage(pageNo, pageSize);


        Example example = new Example(m.getClass());
        Example.Criteria criteria = example.createCriteria().andEqualTo(BeanUtils.setNullValue(m));
        if (StringUtils.isBlank(m.getSortBy())) {
            example.setOrderByClause("create_time desc");
        } else {
            example.setOrderByClause(m.getSortBy());
        }
        List<T> rs = baseService.selectByExample(example);

        PageInfo pageInfo = new PageInfo(rs);
        return new ResponseEntity(pageInfo, HttpStatus.OK);
    }

    @GetMapping("/_all")
    @ApiOperation(value = "查询", authorizations = {@Authorization(value = "apiKey")})
    @WebLog(value = "查询所有")
    public ResponseEntity List(@ApiParam("查询条件实体") T m) throws IllegalAccessException {

        Example example = new Example(m.getClass());
        example.createCriteria().andEqualTo(BeanUtils.setNullValue(m));
        List<T> rs = baseService.selectByExample(example);

        return new ResponseEntity(rs, HttpStatus.OK);
    }

    @PostMapping()
    @ApiOperation(value = "新增", authorizations = {@Authorization(value = "apiKey")})
    @WebLog(value = "新增")
    public ResponseEntity add(@ApiParam("新增实体") @RequestBody @Validated T m, BindingResult result) {

        if (result.hasErrors()) {
            return new ResponseEntity(result.getAllErrors(), HttpStatus.EXPECTATION_FAILED);
        }

        try {
            m.setCreateBy(SecurityUtils.getUsername());
            m.setCreateTime(new Date());
            m.setDeleteFlag("0");
            m.setUpdateCount(0);
            m.setId(baseService.getSequence(BaseModel.BASE_SEQ));
            baseService.save(m);

            return new ResponseEntity("新增成功", HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity("新增失败：" + e.toString(), HttpStatus.EXPECTATION_FAILED);
        }


    }

    @PutMapping("/{id}")
    @ApiOperation(value = "根据ID更新", authorizations = {@Authorization(value = "apiKey")})
    @WebLog(value = "根据ID更新")
    public ResponseEntity update(@PathVariable("id") Integer id, @RequestBody @Validated T m, BindingResult result) {

        if (result.hasErrors()) {
            return new ResponseEntity(result.getAllErrors(), HttpStatus.EXPECTATION_FAILED);
        }

        m.setUpdateBy(SecurityUtils.getUsername());
        m.setUpdateTime(new Date());
        m.setUpdateCount(m.getUpdateCount() == null ? 0 : m.getUpdateCount() + 1);
        baseService.updateNotNull(m);

        return new ResponseEntity(HttpStatus.OK);
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据ID删除", authorizations = {@Authorization(value = "apiKey")})
    @WebLog(value = "根据ID删除")
    public ResponseEntity delete(@PathVariable("id") Integer id) {
        baseService.delete(id);

        return new ResponseEntity(HttpStatus.OK);
    }
}
